"use strict";

/**
 * @auther wtfssd
 * Created by wtfssd on 2017/10/25
 */
import * as React from 'react'

const {View, ScrollView, Image, TouchableOpacity, PanResponder} = require('react-native');
const {connect} = require('react-redux');
const {Actions} = require('react-native-router-flux');
import {SCREEN_HEIGHT, SCREEN_WIDTH} from "../constant";
import {guideStyles, pageCtrStyles} from "../assets/styles/guide";
import {guideItems} from "../assets/data";
import MyText from "../component/MyText";
import {GuideItemStatic, GuidePageCtr} from "../interface/index";
import {AuthPage} from "../interface/router";
import {openUrl} from "../utils/tools";

const GuideItem = (props: GuideItemStatic) => {
    return (
        <View style={guideStyles.guideItemContainer}>
            <MyText style={guideStyles.guideItemTitle}>{props.title}</MyText>
            <View style={guideStyles.guideItemLine}/>
            <MyText style={guideStyles.guideItemText}>{props.content}</MyText>
        </View>
    )
};

const PageCtr = (props: GuidePageCtr) => {
    return (
        <View style={pageCtrStyles.container}>
            {
                (() => {
                    let dots = [];
                    for (let i = 0; i < props.total; i++) {
                        dots.push(<View style={i === props.current ? pageCtrStyles.dotActive : pageCtrStyles.dot}
                                        key={i}/>)
                    }
                    return dots;
                })()
            }
        </View>
    )
};

class GuidePage extends React.Component<AuthPage, any> {

    _panResponder: any;
    _topScrollView: any;
    _guideScrollView: any;
    _topScrollViewOffSetX: number;
    _guideScrollViewOffSetX: number;
    _panOffSet: number;
    _topImageWidth: number;
    _panSpeed: number;

    constructor(props: any, context: any) {
        super(props, context);
        this._topScrollViewOffSetX = 0;
        this._guideScrollViewOffSetX = 0;
        this._panOffSet = 0;
        this._panSpeed = 0;
        this._topImageWidth = SCREEN_HEIGHT * 0.5 * (1554 / 733);
        this.state = {
            currentPage: 0,
        };
        this.initPanResponder();
    }

    componentWillMount(): void {

    }

    componentDidMount(): void {
        this.props.dispatch({
            type: 'auth/firstLaunch'
        })
    }

    /*手势滑动相关*/
    initPanResponder() {
        this._panResponder = PanResponder.create({
            // 要求成为响应者：
            onStartShouldSetPanResponder: (evt, gestureState) => true,
            onStartShouldSetPanResponderCapture: (evt, gestureState) => true,
            onMoveShouldSetPanResponder: (evt, gestureState) => true,
            onMoveShouldSetPanResponderCapture: (evt, gestureState) => true,
            onPanResponderTerminationRequest: (evt, gestureState) => true,
            onShouldBlockNativeResponder: (evt, gestureState) => true,
            onPanResponderGrant: (evt, gestureState) => {

            },
            onPanResponderMove: (evt, gestureState) => {
                // 最近一次的移动距离为gestureState.move{X,Y}
                // 从成为响应者开始时的累计手势移动距离为gestureState.d{x,y}
                this._panOffSet = gestureState.dx;
                this._panSpeed = gestureState.vx;
                this.scrollGuideScrollView();
                this.scrollTopScrollView();

            },

            onPanResponderRelease: this.onPanResponderRelease,
            onPanResponderTerminate: (evt, gestureState) => {
                // 另一个组件已经成为了新的响应者，所以当前手势将被取消。
            },

        });
    }

    onPanResponderRelease = () => {
        const speed = Math.abs(this._panSpeed);
        if ((this._panOffSet > SCREEN_WIDTH * 0.5 ) && this._guideScrollViewOffSetX > 0) {
            this._guideScrollViewOffSetX -= SCREEN_WIDTH;
        } else if ((this._panOffSet < -SCREEN_WIDTH * 0.5) && this._guideScrollViewOffSetX < SCREEN_WIDTH * (guideItems.length - 1)) {
            this._guideScrollViewOffSetX += SCREEN_WIDTH;
        }
        this._guideScrollView.scrollTo({x: this._guideScrollViewOffSetX, animated: true});


        const scrollStep = (this._topImageWidth - SCREEN_WIDTH) / guideItems.length;
        const panRadio = scrollStep / SCREEN_WIDTH;
        if ((this._panOffSet * panRadio > scrollStep * 0.5) && this._topScrollViewOffSetX > 0) {
            this._topScrollViewOffSetX -= scrollStep;
        } else if ((this._panOffSet * panRadio < -scrollStep * 0.5) && this._topScrollViewOffSetX < scrollStep * (guideItems.length - 1)) {
            this._topScrollViewOffSetX += scrollStep;

        }
        this._topScrollView.scrollTo({x: this._topScrollViewOffSetX, animated: true});

        this.setState({currentPage: this._guideScrollViewOffSetX / SCREEN_WIDTH});

    };

    scrollGuideScrollView(): void {
        if (this._panOffSet < 0) {
            if (this._guideScrollViewOffSetX - this._panOffSet > (guideItems.length - 1) * SCREEN_WIDTH) {
            } else {
                this._guideScrollView.scrollTo({
                    x: this._guideScrollViewOffSetX - this._panOffSet,
                    animated: false
                });
            }
        } else {
            if (this._guideScrollViewOffSetX - this._panOffSet <= 0) {

            } else {
                this._guideScrollView.scrollTo({
                    x: this._guideScrollViewOffSetX - this._panOffSet,
                    animated: false
                });
            }
        }
    }

    scrollTopScrollView(): void {
        const scrollStep = (this._topImageWidth - SCREEN_WIDTH) / guideItems.length;
        const panRadio = scrollStep / SCREEN_WIDTH;
        if (this._panOffSet < 0) {
            if (this._topScrollViewOffSetX - this._panOffSet * panRadio > (guideItems.length - 1) * scrollStep) {
            } else {
                this._topScrollView.scrollTo({
                    x: this._topScrollViewOffSetX - this._panOffSet * panRadio,
                    animated: false
                });
            }
        } else {
            if (this._topScrollViewOffSetX - this._panOffSet * panRadio <= 0) {

            } else {
                this._topScrollView.scrollTo({
                    x: this._topScrollViewOffSetX - this._panOffSet * panRadio,
                    animated: false
                });
            }
        }
    }

    onJoinNow = () => {
        openUrl('http://www.hubeihxkj.com', false);
    };

    onLogin = ()=>{
        if(this.props.from === 'auth'){
            Actions.pop({from:'guide'});
        }else {
            Actions.auth({from:'guide'});
        }
    };

    render() {
        return (
            <View style={guideStyles.container}>
                <View style={guideStyles.scrollContainer} {...this._panResponder.panHandlers}>
                    <View style={{height: SCREEN_HEIGHT * 0.5}}>
                        <ScrollView
                            contentContainerStyle={guideStyles.scrollView}
                            horizontal
                            overScrollMode={'never'}
                            scrollEnabled={false}
                            showsHorizontalScrollIndicator={false}
                            ref={(scrollView) => {
                                this._topScrollView = scrollView
                            }}>

                            <Image source={require('../assets/image/guide.png')}
                                   resizeMode={'stretch'}
                                   style={{
                                       height: SCREEN_HEIGHT * 0.5,
                                       width: this._topImageWidth,
                                   }}
                            />
                        </ScrollView>
                    </View>
                    <View style={guideStyles.guideContainer}>
                        <ScrollView
                            contentContainerStyle={guideStyles.scrollView}
                            horizontal
                            pagingEnabled
                            overScrollMode={'never'}
                            scrollEnabled={false}
                            showsHorizontalScrollIndicator={false}
                            ref={(scrollView) => {
                                this._guideScrollView = scrollView
                            }}>
                            {guideItems.map((item: GuideItemStatic, index) => (
                                <GuideItem
                                    key={index}
                                    title={item.title}
                                    content={item.content}/>))}
                        </ScrollView>
                        <PageCtr total={guideItems.length} current={this.state.currentPage}/>
                    </View>
                </View>
                <View>
                    <TouchableOpacity activeOpacity={0.9} onPress={this.onLogin}>
                        <View style={guideStyles.loginBth}>
                            <MyText style={guideStyles.loginText}>登录</MyText>
                        </View>
                    </TouchableOpacity>
                    <TouchableOpacity activeOpacity={0.9} onPress={this.onJoinNow}>
                        <View style={guideStyles.joinBtn}>
                            <MyText style={guideStyles.joinText}>还不是会员？立即加入</MyText>
                        </View>
                    </TouchableOpacity>
                </View>
            </View>
        );
    }
}

export default connect(
    ({sys, auth}) => ({sys, auth})
)(GuidePage);